/*
 * @Description: 映射关系弹窗
 * @Author: Rfan
 * @Date: 2022-07-18 15:26:24
 * @LastEditTime: 2022-09-08 14:19:01
 */

import { useEffect, useState } from 'react';
import { Button, Col, Modal, Row, Select, Space, Table, Typography } from 'antd';
import classNames from 'classnames/bind';
import { v4 as uuidv4 } from 'uuid';
import { fetchMetadata } from '@/api/metadata';
import { indexToTitle } from '@/utils';
import { delItemById, editItemById } from '@/utils/list';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { ILevel } from '@/interfaces/archiveType';
import type { IMetadata } from '@/interfaces/metadata';
import styles from '../../styles/fieldMap.module.scss';

const cx = classNames.bind(styles);

const { Column } = Table;
const { Option } = Select;

interface UploadTemplateDialogProps extends ICommonDialog {
  data?: any; // 模板数据
}

class ExcelItem {
  key: string;

  column: string = '';

  fieldName: string = null;

  fieldOperator: string = '';

  title: string = null;

  titleOperator: string = '';

  constructor(idx: number) {
    this.key = uuidv4();
  }
}

/**
 * @description: 模板配置弹窗
 * @param {UploadTemplateDialogProps} props 弹窗传入参数
 * @return {ReactDOM} 模板配置弹窗tsx
 */
const UploadTemplateDialog: FC<UploadTemplateDialogProps> = (props) => {
  const { visible, data, onClose } = props;

  // 模板数据
  const [template, setTemplate] = useState<any>({});
  // 所有层级的元数据
  const [levelMetadata, setLevelMetadata] = useState<any>({});
  // excel表头下拉框相关
  const [items, setItems] = useState([]);
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  // 新增的表头字段
  const [name, setName] = useState('');

  useEffect(() => {
    if (visible) {
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate: {
          atType: 1,
          atCode: 100,
          level: 1
        }
      };
      !levelMetadata &&
        fetchMetadata(fieldQuery).then((res: any) => {
          setLevelMetadata(res.data);
        });
    }
  }, [visible]);

  useEffect(() => {
    if (data) {
      setTemplate(data);
    }
  }, [data]);

  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 添加选项输入框变化事件
   * @param {any} evt 输入事件
   */
  const onNameChange = (evt: any) => {
    setName(evt.target.value);
  };

  /**
   * @description: 新增一个选项
   * @param {any} evt 按钮点击事件
   */
  const addItem = (evt: any) => {
    evt.preventDefault();
    if (name) {
      setItems([...items, { field_desc: name }]);
      setName('');
    }
  };

  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = [...initTable];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
  };

  /**
   * @description: 清空数据
   * @param {string} key 条目key，用于定位数据
   * @param {any} record 原始条目数据
   */
  const clearItem = (key: string, record: any) => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable(editItemById(key, { ...record, ...initData }, initTable, 'key'));
  };

  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      fieldName: null,
      fieldOperator: '',
      title: null,
      titleOperator: ''
    };
    setInitTable((state) => state.map((item) => ({ ...item, ...initData })));
  };

  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };

  return (
    <Modal
      title="映射关系"
      visible={visible}
      className={cx('field_mapping')}
      width={650}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          onClick={() => {
            onCancel();
          }}
        >
          保存
        </Button>
      ]}
    >
      <Row className={cx('map-title')} justify="space-between">
        <Col>
          <Typography.Text>字段映射</Typography.Text>
        </Col>
        <Col>
          <Space>
            <Button
              onClick={() => {
                setInitTable((state) => [...state, new ExcelItem(state.length)]);
              }}
            >
              增加表头
            </Button>
            <Button
              onClick={() => {
                clearAll();
              }}
            >
              清空
            </Button>
          </Space>
        </Col>
      </Row>
      <Table dataSource={initTable} size="small" pagination={false} bordered>
        <Column
          title="EXCEL列"
          key="excelCol"
          align="center"
          render={(_val, _record, idx) => `${indexToTitle(idx + 1)}1`}
        />
        <Column
          title="档案文件级字段"
          dataIndex="title"
          key="title"
          align="center"
          render={(val, record: ILevel) => (
            <Select
              value={val}
              style={{ width: 140 }}
              size="small"
              placeholder="请选择字段"
              onChange={(value) => {
                handleSave({ ...record, fieldName: value });
              }}
            >
              {items.map((item: IMetadata) => (
                <Option key={item.field_name} value={item.field_name}>
                  {item.field_desc}
                </Option>
              ))}
            </Select>
          )}
        />
        <Column title="关系" key="relation" align="center" render={() => '映射'} />
        <Column
          title="散文件库类型字段"
          dataIndex="fieldName"
          key="fieldName"
          align="center"
          render={(val, record: any) => (
            <Select
              value={val}
              style={{ width: 140 }}
              size="small"
              placeholder="请选择字段"
              onChange={(value) => {
                handleSave({ ...record, fieldName: value });
              }}
            >
              {items.map((item: IMetadata) => (
                <Option key={item.field_name} value={item.field_name}>
                  {item.field_desc}
                </Option>
              ))}
            </Select>
          )}
        />
        <Column
          title="操作"
          dataIndex="action"
          key="action"
          align="center"
          render={(_val, record: any) => (
            <Space size="small">
              <Button
                type="link"
                size="small"
                onClick={() => {
                  clearItem(record.key, record);
                }}
              >
                清空
              </Button>
              <Button
                type="link"
                size="small"
                danger
                onClick={() => {
                  deleteItem(record.key);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
      </Table>
    </Modal>
  );
};

export default UploadTemplateDialog;
